<template>
	<view v-if="chatlist" class="aside-index" ref="uv-back-top">
		<uv-form labelPosition="left" :model="chat" :rules="rules" ref="form">
			<uv-form-item labelWidth="80" label="模型" prop="flux.mode" borderBottom>
				<uni-data-select @change="changes" v-model="chat.model" :localdata="chatlist.model"></uni-data-select>
			</uv-form-item>
			<uv-form-item labelWidth="110" label="是否连续上下文" prop="chat.series" borderBottom>
				<uv-switch class="cursor-pointer" v-model="chat.series" @change=""></uv-switch>
			</uv-form-item>
			<view style="background-color: #dddddd;border-radius: 5px;padding: 5px;">
				<view style="width: 100%;display: flex;justify-content: space-between;">
					<view style="font-weight: bolder;">
						更多其他参数
					</view>
					<view class="cursor-pointer" @click="parmShow = !parmShow" style="padding: 0px 5px;">
						<uv-icon :name="parmShow?'arrow-down':'arrow-left'" size="20"></uv-icon>
					</view>
				</view>
				<view v-if="parmShow" style="margin-top: 10px;margin-left: 5px;">
					<view style="display: flex;justify-content: flex-start;align-items: center;">
						角色设定 <view style="margin-left: 10px;font-size: 12px;color:#666666">
							角色扮演，文案写作，文案仿作
						</view>
					</view>
					<el-input style="margin: 0px;margin-top: 5px;padding-bottom: 12px;" @change="elinput"
						type="textarea" :autosize="{ minRows: 3, maxRows: 5}" maxlength="1000" show-word-limit
						placeholder="给你的会话设置一个专属的角色，不是必须" v-model="textarea">
					</el-input>
				</view>
			</view>
			<view v-if="false" style="padding: 10px; display: flex;justify-content: space-between;align-items: center;">
				<view class="">
					更多其他参数
				</view>
				<uv-switch v-model="more"></uv-switch>
			</view>
			<view v-if="more">
				<uv-form-item labelWidth="80" label="回复数" prop="chat.max_tokens" borderBottom>
					<view style="width: 100%;padding: 0px 10px;">
						<el-slider :min="1" :max="4096" v-model="chat.max_tokens"></el-slider>
					</view>
				</uv-form-item>
				<uv-form-item labelWidth="80" label="角色设定" prop="chat.name" borderBottom>
					<el-input @change="elinput" @input="elinput" type="textarea" :autosize="{ minRows: 2, maxRows: 4}"
						placeholder="给你的会话设置一个专属的角色，不是必须" v-model="textarea">
					</el-input>
					<!-- <uv-input style="height: 400px;" placeholder="请输入内容" border="surround" clearable></uv-input> -->
				</uv-form-item>
				<uv-form-item labelWidth="80" label="聊天完成选项" prop="chat.n" borderBottom>
					<view style="width: 100%;padding: 0px 10px;">
						<el-slider :min="0" :max="10" v-model="chat.n"></el-slider>
					</view>
				</uv-form-item>
				<uv-form-item labelWidth="80" label="令牌" prop="chat.stop" borderBottom>
					<view style="width: 100%;padding: 0px 10px;">
						<el-slider :min="0" :max="4" v-model="chat.stop"></el-slider>
					</view>
				</uv-form-item>
				<uv-form-item labelWidth="80" label="随机性" prop="chat.temperature" borderBottom>
					<view style="width: 100%;padding: 0px 10px;">
						<el-slider :format-tooltip="e=> formatValue(e,'temperature')" v-model="temperature"></el-slider>
					</view>
				</uv-form-item>
				<uv-form-item labelWidth="80" label="核采样" prop="chat.top_p" borderBottom>
					<view style="width: 100%;padding: 0px 10px;">
						<el-slider :format-tooltip="e=> formatValue(e,'top_p')" v-model="top_p"></el-slider>
					</view>
				</uv-form-item>
				<uv-form-item labelWidth="80" label="话题新鲜度" prop="chat.presence_penalty" borderBottom>
					<view style="width: 100%;padding: 0px 10px;">
						<el-slider :format-tooltip="e=> formatValue(e,'presence_penalty')"
							v-model="chat.presence_penalty"></el-slider>
					</view>
				</uv-form-item>
				<uv-form-item labelWidth="80" label="频率惩罚度" prop="chat.frequency_penalty" borderBottom>
					<view style="width: 100%;padding: 0px 10px;">
						<el-slider :format-tooltip="e=> formatValue(e,'frequency_penalty')"
							v-model="chat.frequency_penalty"></el-slider>
					</view>
				</uv-form-item>
				<uv-form-item labelWidth="80" label="TTS语音人物" prop="chat.name" borderBottom>
					<view class="chat_content"
						style="width:100% ; display: flex;justify-content: flex-start;align-items: center;flex-wrap: wrap;">
						<!-- <view style="margin-right: 20px;" v-for="(item, index) in chatlist" :key="index">
							<uv-tags :text="`Ai${index + 1}`" :plain="index != radiosval" type="warning" :name="index"
								@click="radiosval= index">
							</uv-tags>
						</view> -->
					</view>
				</uv-form-item>
			</view>
			<el-link style="font-size: 12px;opacity: 0;height: 0px !important;" type="primary">{{fill}}</el-link>
			<view style="display: flex;justify-content: space-between;margin-bottom: 10px;">
				<uv-button type="primary" text="保存" style="width: 49%;" @click="submit"></uv-button>
				<uv-button type="error" text="重置" style="width: 49%;" @click="reset"></uv-button>
			</view>
		</uv-form>
		<uv-toast ref="toast"></uv-toast>
	</view>
</template>

<script>
	// 引入
	import tabbars from '@/components/tabbar/tabbar';
	import {
		task,
		index,
		taskId,
		getScroll,
		scroll,
	} from '@/common/api.js';
	import config from '@/common/config'
	import {
		string
	} from '../../../uni_modules/uv-ui-tools/libs/function/test';
	export default {
		components: {
			// 注册组件
		},
		props: {
			chatlist: {
				type: [Object, Array],
			},
			minWidth: {
				type: [Number, String],
				default: 1
			},
			aside: {
				type: Boolean,
				default: false
			},
			asideW: {
				type: Number,
				default: 250
			},
			deepColor: {
				type: String,
				default: '#4D4D4D'
			},
			shallowColor: {
				type: String,
				default: '#808080'
			},
			lightColor: {
				type: String,
				default: '#ccc'
			},
			// aicurrent: {
			// 	type: Number,
			// 	default: 0
			// },
		},
		data() {
			return {
				fill: config.fill,
				tabbarsValue: 'chat',
				scrollTop: 0,
				isFirstLoad: true, // 标志变量，用于判断是否首次加载
				value: '',
				id: '',
				data: [],
				parmShow: true,
				createdAt: '',
				textarea: "",
				more: false,
				temperature: 50,
				top_p: 100,
				presence_penalty: 0,
				frequency_penalty: 0,
				chat: {
					series: true
				},
				dataLoaded: false,
				rules: {
					'userInfo.name': {
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					},
					'userInfo.sex': {
						type: 'string',
						max: 1,
						required: true,
						message: '请选择男或女',
						trigger: ['blur', 'change']
					},
				},
			}
		},
		watch: {
			// 监听data数据的变化
			chat: {
				handler: function(newVal, oldVal) {
					// this.$uv.vuex('config_' + this.tabbarsValue, newVal);
					// this.$emit('custom-type', newVal);
					this.$emit('custom-event', newVal);
				},
				deep: true
			},
			// aicurrent: {
			// 	handler: function(newVal, oldVal) {
			// 		console.log(newVal);
			// 		this.reset();
			// 		this.$uv.vuex('chatCurrent', newVal);
			// 	},
			// 	deep: true
			// },
			chatlist(newVal, oldVal) {
				if (newVal) {
					var chat = this['config_' + this.tabbarsValue];
					if (chat && chat.ai && !this.chat.ai) {
						this.chat = {
							ai: chat.ai,
							text: chat.text,
							model: chat.model,
							tag: chat.tag,
							series: chat.series,
							messages: chat.messages,
							n: chat.n,
							temperature: chat.temperature,
							top_p: chat.top_p,
							presence_penalty: chat.presence_penalty,
							frequency_penalty: chat.frequency_penalty,
						};
					} else {
						this.reset();
					}
				}
			},
			top_p: {
				handler: function(newVal, oldVal) {
					this.chat['top_p'] = newVal / 100;
				},
				deep: true
			},
			presence_penalty: {
				handler: function(newVal, oldVal) {
					this.chat['presence_penalty'] = newVal / 100;
				},
				deep: true
			},
			frequency_penalty: {
				handler: function(newVal, oldVal) {
					this.chat['frequency_penalty'] = newVal / 100;
				},
				deep: true
			},
		},
		mounted() {
			var that = this;
			this.tabbarsValue = this.pages();
		},
		methods: {
			changes(e) {
				var model = this.chatlist.model;
				for (let ind = 0; ind < model.length; ind++) {
					const eleme = model[ind];
					if (eleme.value == e) {
						this.chat['tag'] = eleme.tag;
						this.chat['text'] = eleme.text;
					}
				}
			},
			reset() {
				this.chat = {
					ai: this.chatlist.value,
					text: this.chatlist.model[0].text,
					model: this.chatlist.model[0].value,
					tag: this.chatlist.model[0].tag,
					series: true,
					messages: [],
					n: 0,
					temperature: 0,
					top_p: 0,
					presence_penalty: 0,
					frequency_penalty: 0,
				};
			},
			submit() {
				this.$emit('custom-event', this.chat);
				this.$emit('submit');
			},
			elinput() {
				if (this.textarea) {
					this.chat['messages'] = [{
						"role": "system",
						"content": this.textarea
					}]
				} else {
					this.chat['messages'] = [];
				}
			},
			formatValue(val, name) {
				this.chat[name] = val / 100;
				return val / 100;
			},
			async getVuex() {
				getScroll({
					custom: {
						auth: true,
						toast: false,
					},
					params: {
						type: this.tabbarsValue,
					}
				}).then(data => {
					if (data && data.content) {
						this.$uv.vuex('vuex_' + this.tabbarsValue, data.content);
					}
				})
			},
			async record() {
				await scroll({
					content: this['vuex_' + this.tabbarsValue],
					type: this.tabbarsValue
				}, {
					custom: {
						auth: true,
						toast: false,
					},
				})
			},
			cTime(time1, data, index) {
				if (index == 0) {
					return true;
				}
				// console.log(" ” " + Number(data.length - 1));
				if (index == Number(data.length - 1)) {
					return false;
				}
				var time2 = data[index + 1] && data[index + 1].createdAt;
				if (!time1 || !time2) {
					return false;
				}
				// console.log(time1 + " 《=》 " + time2);
				// 将时间转换为Date对象
				var date1 = new Date(time1).getTime();
				var date2 = new Date(time2).getTime();
				// 计算时间差（毫秒）
				var difference = Math.abs(date2 - date1);
				// 将时间差转换为分钟
				var minutes = Math.ceil(difference / (1000 * 60)); // 向上取整
				if (minutes > 20) {
					return true;
				} else {
					return false;
				}
			},
			times(time) {
				return " -- " + uni.$uv.timeFrom(new Date(time).getTime()) + " -- ";
			},
			routes(url) {
				this.routed('/pages' + url);
			},
			pages() {
				var pages = getCurrentPages() // 获取栈实例
				let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由
				let currentPage = pages[pages.length - 1]['$page']['fullPath'] //当前页面路径(带参数)
				return currentPage.split('/')[2];
			},
			routed(url) {
				console.log('routed', url)
				uni.$uv.route({
					url: url,
					intercept(params, next) {
						console.log(params, next)
						uni.showLoading({
							title: '等待中...'
						})
						// 模拟处理等待
						setTimeout(() => {
							uni.hideLoading();
							next(true);
						}, 1000)
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	@import "@/uni_modules/uv-ui-tools/index.scss";

	.aside-index {
		transition: width 2s;
	}
</style>